package br.com.etecmatao.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

    private final static String FILTER_APPLIED = "_security_filter_applied";

    public LoginFilter() {
    }

    public void init(FilterConfig arg0) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hreq = (HttpServletRequest) request;
        HttpServletResponse hresp = (HttpServletResponse) response;
        HttpSession session = hreq.getSession();

        hreq.getPathInfo();
        String paginaAtual = new String(hreq.getRequestURL());

        if ((request.getAttribute(FILTER_APPLIED) == null) && paginaAtual != null
                && (!paginaAtual.contains("/admin"))
                &&(!paginaAtual.endsWith("login.xhtml"))) {
            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
        }
            if (session.getAttribute("user") == null && (paginaAtual.contains("/admin")) && !(paginaAtual.contains("login.xhtml"))) {
                hresp.sendRedirect("login.xhtml");
                return;
            }
        
        chain.doFilter(request, response);
    }
}
